namespace Viyi.Util.Linq;

public static partial class EnumerableExtensions {
    /// <summary>
    /// 等同于无参数的 ForEach()，目的是为了执行 Enumerable 的遍历
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    public static void Enumerate<T>(this IEnumerable<T> source) {
        foreach (var it in source) { }
    }

    /// <summary>
    /// Enumerate 的别名，目的是为了执行 Enumerable 的遍历
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    public static void ForEach<T>(this IEnumerable<T> source) => Enumerate(source);

    public static void ForEach<T>(this IEnumerable<T> source, Action<T> process) {
        foreach (var it in source) { process(it); }
    }

    public static void ForEach<T>(this IEnumerable<T> source, Action<T, int> process) {
        foreach (var (it, index) in source.Select((it, index) => (it, index))) {
            process(it, index);
        }
    }

    public static void ForEach<T, R>(this IEnumerable<T> source, Func<T, R> process) {
        foreach (var it in source) { process(it); }
    }

    public static void ForEach<T, R>(this IEnumerable<T> source, Func<T, int, R> process) {
        source.Select(process).Enumerate();
    }

    public static async Task ForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> process) {
        foreach (var it in source) { await process(it); }
    }

    public static async Task ForEachAsync<T>(this IEnumerable<T> source, Func<T, int, Task> process) {
        foreach (var (it, index) in source.Select((it, index) => (it, index))) {
            await process(it, index);
        }
    }

    public static async Task ForEachAsync<T, R>(this IEnumerable<T> source, Func<T, Task<R>> process) {
        foreach (var it in source) { await process(it); }
    }

    public static async Task ForEachAsync<T, R>(this IEnumerable<T> source, Func<T, int, Task<R>> process) {
        foreach (var (it, index) in source.Select((it, index) => (it, index))) {
            await process(it, index);
        }
    }
}
